package storages

import (
	"github.com/pkg/errors"
	"gluenet/internal/glue-srvm/model"
	"gorm.io/gorm"
)

type dictStorage struct{}

var DefaultDictStorage = &dictStorage{}

func (c *dictStorage) Insert(db *gorm.DB, data model.Dict) (uint, error) {
	return uint(data.Id), errors.WithStack(db.Create(&data).Error)
}

func (c *dictStorage) Update(db *gorm.DB, filter, data model.Dict) error {
	return errors.WithStack(db.Model(data).Where(&filter).Updates(&data).Error)
}

func (c *dictStorage) DeleteByID(db *gorm.DB, id uint) error {
	if id == 0 {
		return errors.New("ID cannot be empty.")
	}
	return errors.WithStack(db.Delete(&model.Dict{Id: uint64(id)}).Error)
}

func (c *dictStorage) FindOne(db *gorm.DB, filter model.Dict) (*model.Dict, error) {
	var dict model.Dict
	err := db.Where(&filter).Find(&dict).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, nil
	}
	return &dict, errors.WithStack(err)
}

func (c *dictStorage) FindAll(db *gorm.DB, filter model.Dict) ([]model.Dict, error) {
	var dicts []model.Dict
	err := db.Where(&filter).Find(&dicts).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errors.WithStack(err)
	}
	return dicts, nil
}
